# -*- coding: utf-8 -*-
  # version:python2.7.13
   # author:yjy
  
  # 导入相关模块
   import urllib2
   import time, xlwt, os,json
   from PIL import Image
  
 # 使用face++的api识别情绪
  def useapi(img):
     http_url = 'https://api-cn.faceplusplus.com/facepp/v3/detect'
     boundary = '----------%s' % hex(int(time.time() * 1000))
      data = []
      data.append('--%s' % boundary)
     data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_key')
     data.append(key)
     data.append('--%s' % boundary)
     data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_secret')
     data.append(secret)
     data.append('--%s' % boundary)
      fr = open(img, 'rb')
     data.append('Content-Disposition: form-data; name="%s"; filename=" "' % 'image_file')
      data.append('Content-Type: %s\r\n' % 'application/octet-stream')
     data.append(fr.read())
      fr.close()
     data.append('1')
     data.append('--%s' % boundary)
     data.append('Content-Disposition: form-data; name="%s"\r\n' % 'return_attributes')
      data.append("gender,age,emotion,ethnicity")# 这里可以还可以返回其他参数，具体可以参看face++的api文档
     data.append('--%s--\r\n' % boundary)
 
     http_body = '\r\n'.join(data)
      # build http request
     req = urllib2.Request(http_url)
     # header
     req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
     req.add_data(http_body)
     try:
         resp = urllib2.urlopen(req,timeout=5)
         qrcont = json.load(resp)
    except urllib2.HTTPError as e:
         print e.read()
     return qrcont
 
 
  # 将json字典写入excel
  # 变量用来循环时控制写入单元格，感觉这种方式有点傻，但暂时想不到优化方法
  def writeexcel(img, worksheet, row, files_name):
      parsed = useapi(img)
     if not parsed['faces']:
         print 'This picture do not have any face'
     else:
          if len(parsed['faces'])<=5: # 由于免费API限制，只能返回5张人脸信息
             for list_item in parsed['faces']:
                 # 写入文件名
                  filename, extension = os.path.splitext(files_name)
                 worksheet.write(row, 0, filename)
 
                 # 写入时间戳
                 daystamp, timestamp, hourstamp = gettimestamp(img)
                worksheet.write(row, 1, label=daystamp)
                 worksheet.write(row, 2, label=timestamp)
                worksheet.write(row, 3, hourstamp)
 
                 # 写入api返回的数据
                 emotion = []
                 for key1, value1 in list_item.items():
                     if key1 == 'attributes':
                         for key2, value2 in value1.items():
                             if key2 == 'age':
                                worksheet.write(row, 5, value2['value'])
                            elif key2 == 'emotion':
                                 for key3, value3 in value2.items():
                                     if key3 == 'sadness':
                                         worksheet.write(row, 8, value3)
                                         emotion.append(value3)
                                     elif key3 == 'neutral':
                                         worksheet.write(row, 9, value3)
                                         emotion.append(value3)
                                     elif key3 == 'disgust':
                                         worksheet.write(row, 10, value3)
                                         emotion.append(value3)
                                     elif key3 == 'anger':
                                          worksheet.write(row, 11, value3)
                                       emotion.append(value3)
                                    elif key3 == 'surprise':
                                         worksheet.write(row, 12, value3)
                                         emotion.append(value3)
                                      elif key3 == 'fear':
                                         worksheet.write(row, 13, value3)
                                         emotion.append(value3)
                                     else:
                                         worksheet.write(row, 14, value3)
                                         emotion.append(value3)
                             elif key2 == 'gender':
                                  worksheet.write(row, 6, value2['value'])
                             elif key2 == 'ethnicity':
                                 worksheet.write(row, 7, value2['value'])
                            else:
                                 pass
                     elif key1 == 'face_token':
                       worksheet.write(row, 4, value1)
                    else:
                         pass
                 worksheet.write(row, 15, emotion.index(max(emotion)))
            # 写入概率最大的情绪，0-neutral,1-sadness,2-disgust，3-anger，4-surprise，5-fear，6-happiness
109                 row += 1
        else:
            for list_item in parsed['faces'][0:5]:
                 # 写入文件名
                filename, extension = os.path.splitext(files_name)
                 worksheet.write(row, 0, filename)
 
                # 写入时间戳
                daystamp, timestamp, hourstamp = gettimestamp(img)
               worksheet.write(row, 1, label=daystamp)
               worksheet.write(row, 2, label=timestamp)
                worksheet.write(row, 3, hourstamp)

                # 写入api返回的数据
                emotion = []
                 for key1, value1 in list_item.items():
                     if key1 == 'attributes':
                         for key2, value2 in value1.items():
                            if key2 == 'age':
                                worksheet.write(row, 5, value2['value'])
                            elif key2 == 'emotion':
                                for key3, value3 in value2.items():
                                    if key3 == 'sadness':
                                        worksheet.write(row, 8, value3)
                                         emotion.append(value3)
                                         print '1'
                                     elif key3 == 'neutral':
                                         worksheet.write(row, 9, value3)
                                       emotion.append(value3)
                                        print '2'
                                    elif key3 == 'disgust':
                                        worksheet.write(row, 10, value3)
                                         emotion.append(value3)
                                         print '3'
                                     elif key3 == 'anger':
                                        worksheet.write(row, 11, value3)
                                         emotion.append(value3)
                                         print '4'
                                    elif key3 == 'surprise':
                                         worksheet.write(row, 12, value3)
                                        emotion.append(value3)
                                         print '5'
                                    elif key3 == 'fear':
                                        worksheet.write(row, 13, value3)
                                        emotion.append(value3)
                                        print '6'
                                    else:
                                         worksheet.write(row, 14, value3)
                                       emotion.append(value3)
                                      print '7'
                           elif key2 == 'gender':
                                worksheet.write(row, 6, value2['value'])
                            elif key2 == 'ethnicity':
                                 worksheet.write(row, 7, value2['value'])
                             else:
                                 pass
                     elif key1 == 'face_token':
                         worksheet.write(row, 4, value1)
                     else:
                         pass
                worksheet.write(row, 15, emotion.index(max(emotion)))
                 # 写入概率最大的情绪，0-neutral,1-sadness,2-disgust，3-anger，4-surprise，5-fear，6-happiness
                 row += 1
                 print 'Success! The pic ' + str(files_name) + ' was detected!'
 
     return row, worksheet
 
 # 获取图片大小
def imagesize(img):
     Img = Image.open(img)
     w, h = Img.size
     return w,h
 
 # 获取时间戳
 def gettimestamp(path):
     statinfo = os.stat(path)
     timeinfo = time.localtime(statinfo.st_ctime)
    daystamp = str(timeinfo.tm_year) + '-' + str(timeinfo.tm_mon) + '-' + str(timeinfo.tm_mday)
     timestamp = str(timeinfo.tm_hour) + ':' + str(timeinfo.tm_min) + ':' + str(timeinfo.tm_sec)
     hourstamp = timeinfo.tm_hour + timeinfo.tm_min / 60.0 + timeinfo.tm_sec / 3600.0
    return daystamp, timestamp, hourstamp
 
 
 key = "WsfrI9ff0RGQgOItOQ2g5pK1RQxUXAJ5"
 secret = "qlJE-D0tfO0NMrqC3TQfsTfYSnHj-Y08"
 path = r"face"
 # 注意：由于我是对同一文件夹下的多个文件夹中的图片进行识别，所以这个path是图片所在文件夹的上一级文件夹。文件夹名尽量使用英文与数字，不然可能因为编码问题报错

# 创建excel
 workbook = xlwt.Workbook(encoding='utf-8')
 
for root, dirs, files in os.walk(path, topdown=False):
     for folder in dirs:
        print 'Let us start dealing with folder ' + folder
 
        # 创建一个新的sheet
         worksheet = workbook.add_sheet(folder)
         # 设置表头
        title = ['PhotoID', 'daystamp', 'timestamp', 'hourstamp','faceID', 'age', 'gender', 'ethnicity', 'sadness',
                  'neutral','disgust', 'anger', 'surprise', 'fear', 'happiness', 'emotion']
         for col in range(len(title)):
             worksheet.write(0, col, title[col])
 
        # 遍历每个folder里的图片
         row = 1
        for root2, dirs2, files2 in os.walk(path + '\\' + folder):
             for files_name in files2:
                 img = path + '\\' + folder + '\\' + files_name
                try:
                    print 'Now, the program is going to deal with ' + folder + ' pic' + str(files_name)
                     w,h=imagesize(img)
                    if w<48 or h<48 or w>4096 or h>4096:#API对图片大小的限制
                         print 'invalid image size'
                     else:
                         row, worksheet = writeexcel(img, worksheet, row, files_name)
 
                 except:
                     print '超过了并发数！等一下！'
                    time.sleep(3)
                    print 'The program is going to work'
                     print 'Now, the program is going to deal with ' + folder + ' pic' + str(files_name)
                     row, worksheet = writeexcel(img, worksheet, row, files_name)
 
        workbook.save('detactface_facepp_flickr.xls')
         print 'The current folder is done.'
 
 # 保存文件
 workbook.save('detectface.xls')
 print 'All done!'

